{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from collections import Counter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def find_min(freq):\n",
    "    item = min(freq, key=lambda i: i[0])\n",
    "    freq.remove(item)\n",
    "    return item"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def huffman_codes(text):\n",
    "    freq = [(i, x) for x, i in Counter(text).items()]\n",
    "\n",
    "    while len(freq) > 1:\n",
    "        li, lx = find_min(freq)\n",
    "        ri, rx = find_min(freq)\n",
    "        freq.append((li + ri, (lx, rx)))\n",
    "\n",
    "    print_codes(freq.pop()[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def print_codes(tree, prefix=''):\n",
    "    if isinstance(tree, tuple):\n",
    "        print_codes(tree[0], prefix + '0')\n",
    "        print_codes(tree[1], prefix + '1')\n",
    "    else:\n",
    "        print(tree, prefix)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a 0\n",
      "b 10\n",
      "c 11\n"
     ]
    }
   ],
   "source": [
    "huffman_codes('abca')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "i 000\n",
      "  001\n",
      "t 01\n",
      "l 1000\n",
      "v 1001\n",
      "s 101\n",
      "a 11\n"
     ]
    }
   ],
   "source": [
    "huffman_codes('astala vista tasta')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
